package ebj.common.queue;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.gson.Gson;

import ebj.common.queue.meta.QueryEntry;

/**
 * <p>生产者线程</p>
 * @since V1.0
 * @Author Martin
 * @createTime 2014年5月13日 下午5:26:33
 * @modifiedBy name
 * @modifyOn dateTime
 */
public class Producer implements Runnable {

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        // String data = null;
        QueryEntry data = null;
        Random r = new Random();

        System.out.println("启动生产者线程！");
        try {
            while (isRunning) {
                System.out.println("正在生产数据...");
                Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));

                // data = "data:" + count.incrementAndGet();
                data = new QueryEntry(UUID.randomUUID().toString().replace("-", ""), "query_paramepers" + String.valueOf(count.incrementAndGet()));
                System.out.println("将数据：" + new Gson().toJson(data) + "放入队列...");
                if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
                    System.out.println("放入数据失败：" + data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            System.out.println("退出生产者线程！");
        }
    }

    public void stop() {
        isRunning = false;
    }

    private volatile boolean isRunning = true;
    private BlockingQueue<QueryEntry> queue;
    private static AtomicInteger count = new AtomicInteger();
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;

}
